import 'package:english_words/english_words.dart';
import 'package:fish_redux/fish_redux.dart';

import 'action.dart';
import 'state.dart';

Reducer<HomePageState> buildReducer() {
  return asReducer(
    <Object, Reducer<HomePageState>>{
      HomePageAction.init: _init,
      HomePageAction.randomMsg: _randomMsg,
      HomePageAction.refresh: _refresh,
      HomePageAction.fetch: _fetch,
    },
  );
}

HomePageState _init(HomePageState state, Action action) {
  final HomePageState payload = action.payload ?? HomePageState();
  final HomePageState newState = state.clone();

  newState.msg = payload.msg;
  newState.words = payload.words;
  newState.refreshController = payload.refreshController;

  return newState;
}

HomePageState _randomMsg(HomePageState state, Action action) {
  final HomePageState payload = action.payload ?? HomePageState();
  final HomePageState newState = state.clone();

  newState.msg = payload.msg;

  return newState;
}

HomePageState _refresh(HomePageState state, Action action) {
  final List<WordPair> payload = action.payload ?? <WordPair>[];
  final HomePageState newState = state.clone();

  newState.words = payload;

  return newState;
}

HomePageState _fetch(HomePageState state, dynamic action) {
  final List<WordPair> payload = action.payload ?? <WordPair>[];
  final HomePageState newState = state.clone();

  newState.words = newState.words.followedBy(payload).toList();

  return newState;
}
